//
// Created by Max on 2025/5/28.
//

#include "MicLoader.h"
#include "MicConfig.h"
#include <tinyalsa/asoundlib.h>

MicConfig::MicConfig() {

    LOGD("MicConfig MicConfig");
}

MicConfig::~MicConfig() {

}

int MicConfig::Init(int channelNum, int sampleRate) {
    struct pcm_config config;
    memset(&config, 0, sizeof(config));

    config.channels = channelNum;
    config.rate = 16000;
    config.period_size = 256;
    config.period_count = 8;
    config.format = PCM_FORMAT_S16_LE;
    config.start_threshold = 0;
    config.stop_threshold = 0;
    config.silence_threshold = 0;

    mPcm = pcm_open(0, 0, PCM_IN, &config);
    if (!mPcm || !pcm_is_ready(mPcm)) {
        LOGE("Unable to open PCM device (%s)\n",
             pcm_get_error(mPcm));
        return MI_FAILURE;
    }
    return MI_SUCCESS;
}

int MicConfig::DeInit() {
    if (mPcm == nullptr)
        return MI_SUCCESS;
    return pcm_close(mPcm);
}

int MicConfig::readMic(void *data, unsigned int frame_count) {
    if (mPcm == nullptr){
        LOGE("Recorder don't Init !");
        return MI_FAILURE;
    }
    return pcm_readi(mPcm,data,frame_count);
}

uint32_t MicConfig::pcmFrames2Bytes(uint32_t frames) {
    if (mPcm == nullptr){
        LOGE("Recorder don't Init !");
        return JNI_FALSE;
    }
    return pcm_frames_to_bytes(mPcm,frames);

}

uint32_t MicConfig::pcmGetBufferSize() {
    if (mPcm == nullptr){
        LOGE("Recorder don't Init !");
        return JNI_FALSE;
    }
    return pcm_get_buffer_size(mPcm);
}